import Vue from 'vue';
import App from './App';
import router from './router/router';
import store from './store/store';
// import {apiReady} from './common/js/initApiApp';
Vue.prototype.limitIntegers = function( val ){
  //输入框限制输入整数
  return val.replace(/^(0+)|[^\d]+/g,'')
};
// Vue.prototype.apiApp = function(){
//   return new Promise(async (resolve , reject) => {
//     if(apiReady.isReady){
//       resolve(apiReady)
//     } else {
//       let app = await apiReady.ready();
//       console.log('抓取app2222222222+++'+JSON.stringify(app));
//       resolve(app);
//     }
//   });
// };
Vue.prototype.log = function (mark, logtext) {
  // 用于在 app apicloud 端输出
  let mk = mark ? mark : '---';
  if ( logtext instanceof Array || logtext instanceof Object) {
    logtext = JSON.stringify(logtext);
  }
  console.log(mk + " --- " + logtext);
};
Vue.prototype.cover = bl =>{
  //公共显示隐藏Cover，调用 this.cover( bl ) ; bl为true显示，否则隐藏
  let show = bl && bl == true || bl == false ? bl : true;
  store.commit('cover' , show);
};
Vue.prototype.loading = function () {
  store.commit('isLoading',true); //全局公用显示加载动画方法： this.loading() 或者 store.commit('isLoading',true);
};
Vue.prototype.closeLoading = function () {
  store.commit('isLoading',false); //全局公用关闭加载动画方法： this.closeLoading() 或者 store.commit('isLoading',false);
};
Vue.prototype.type = function(arg) {    //判断类型返回 object array function string number undefined ....
  if (arg) return Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
};
Vue.prototype.for = function(tar  , callback){
  let typeTar = this.type(tar);
  switch (typeTar) {
    case  'array':
      for(let index = 0 , len = tar.length; index < len ; index++)
        callback(tar[index] , index);
      break;
    case 'filelist':
      for(let index = 0 , len = tar.length; index < len ; index++)
        callback(tar[index] , index);
      break;
    case 'object':
      for( let key in tar )
        callback(tar[key] , key);
      break;
  }
};
Vue.prototype.testMobile = function ( mob_phone ) {
  return mob_phone != "" && (/^[0-9]{9,}$/).test(mob_phone)  /*正则匹配手机*/
};
Vue.prototype.delCharacter = ( value ) =>{
  /*删除字符，例如输入姓名，不允许输入字符*/
  return value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'');
};
Vue.prototype.numSlice = function( str , len ){
  //截取小数长度
  let result = String( str );
  if( len || typeof len == "number" ){
    result = String( result ).split('.');
    try {
      let left = result[0];
      let right = result[1].slice(0 , len );
      // console.log('left' , left);
      // console.log('right' , right)
      result =left + '.' + right;
    }
    catch (e) {
      result = Number( result[0] );
    }
  }
  return result;
};
Vue.prototype.scientificToNumber = function(num) {
  //科学计数法
  var str = num.toString();
  var reg = /^(\d+)(e)([\-]?\d+)$/;
  var arr, len, zero = '';
  /*6e7或6e+7 都会自动转换数值*/
  if (!reg.test(str)) {
    return num;
  } else {
    /*6e-7 需要手动转换*/
    arr = reg.exec(str);
    len = Math.abs(arr[3]) - 1;
    for (var i = 0; i < len; i++) {
      zero += '0';
    }
    return '0.' + zero + arr[1];
  }
};
Vue.prototype.accMul = ( arg1 , arg2 , len )=>{
  /*高精度乘法*/
  //len，保留小数长度
  let max = 0, s1 = ''+arg1, s2 = ''+arg2;
  try { max += s1.split(".")[1].length } catch (e) { }
  try { max += s2.split(".")[1].length } catch (e) { }
  let result = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, max);
  return result
};
Vue.prototype.accMoreMul = function () {
  //多个高精度乘法
  let a = 1 ,
    thiz = this;
  for (var i in arguments) {
    a = thiz.accMul(a, arguments[i])
  }
  return a
};
Vue.prototype.sliceNum = function (num, digit) {
  //截取小数
  let re = new RegExp('([0-9]+\.[0-9]{0,' + digit + '})[0-9]*');
  let thisNum = String(num).replace(re, "$1");
  return thisNum
};
Vue.prototype.accSub = function(arg1, arg2){
  //高精度减法
  let r1, r2, max, min;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  max = Math.pow(10, Math.max(r1, r2));
  //动态控制精度长度
  min = (r1 >= r2) ? r1 : r2;
  return ((arg1 * max - arg2 * max) / max).toFixed(min)
};
Vue.prototype.accDiv = function(arg1, arg2 , len ) {
  //高精度除法
  //sli_len 保留小数长度
  let t1 = 0, t2 = 0, r1, r2;
  try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
  try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
  // with (Math) {
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  let result = (r1 / r2) * Math.pow(10, t2 - t1);
  if( len) {result =  this.numSlice( result , len );}
  return result;
}
Vue.prototype.accAdd = function(arg1, arg2) {
  //高精度加法
  let r1, r2, max;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  max = Math.pow(10, Math.max(r1, r2));
  return (arg1 * max + arg2 * max) / max
};
Vue.prototype.accAddMore = function(){
  //加法，多个值
  let accAdd = function(arg1, arg2) {
    let r1, r2, max;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    max = Math.pow(10, Math.max(r1, r2));
    return (arg1 * max + arg2 * max) / max
  };
  let args = arguments;
  let result = 0;
  if( args.length >= 2 ){
    for( let i = 0 ; i < args.length ; i++ ){
      result = accAdd( result , String(args[i]));
    }
  }
  return result;
};
Vue.prototype.formatDate = (value) => {
  /*秒数-转变年月日时分秒*/
  if (!value) {
    return '';
  } else {
    let msData = Number(value)* 1000;
    const date = new Date(msData);
    const y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
  }
};
Vue.config.productionTip = false;
Vue.prototype.browserType = function(){
  let sUserAgent = navigator.userAgent.toLowerCase();
  let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
  let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
  let bIsMidp = sUserAgent.match(/midp/i) == "midp";
  let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
  let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
  let bIsAndroid = sUserAgent.match(/android/i) == "android";
  let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
  let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
  if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
    return 1;
  } else {
    return 2;
  }
};
Vue.prototype.toBottom = function ( callback  ) {
  //到底加载
  //thiz.loadMore = function(){  loadList()  }
  //window.addEventListener('scroll',thiz.loadMore,true);
  // let scr = Math.ceil(  document.documentElement.scrollTop || document.body.scrollTop ) ; // 滚动高度
  // let clientHeight = window.screen.height ||  window.innerHeight || document.documentElement.clientHeight; // 屏幕高度（包含浏览器工作栏）
  // let scrHeight =  document.documentElement.scrollHeight || document.body.scrollHeight; // html高度
  // let one = Math.ceil(this.accAdd(scr , clientHeight ));
  // console.log('one' , one);
  // console.log('scrHeight' , scrHeight);
  // if(one >= scrHeight){
  //   callback();  /*公共：页面滑动到底部加载*/
  // }
  //浮动框变化的高度
  const height1 = document.documentElement.scrollTop || document.body.scrollTop;
  //屏幕的高度
  let thiz = this;
  const height2 = function (){
    if( thiz.browserType() === 1  ){
      return window.screen.height ||  window.innerHeight || document.documentElement.clientHeight;
    }else{
      return  document.documentElement.clientHeight || document.body.clientHeight;
    }
  };
  //id=list-box的高度（列表信息放在这个标签里）
  const height3 = document.documentElement.scrollHeight || document.body.scrollHeight;
  let left = Math.ceil( this.accAdd(height1 ,  height2() ) );
  // console.log('window.screen.height',window.screen.height)
  // console.log('document.documentElement.clientHeight',document.documentElement.clientHeight)
  // console.log('height1',height1)
  // console.log('height2',height2());
  // console.log('left',left);
  // console.log('height3',height3);
  if ( left >= height3 ) {
    callback()
  }

};
Vue.prototype.noScroll = function () {
  let mo=function(e){e.preventDefault();};
  document.body.style.overflowY='hidden';
  document.getElementById('app').style.overflowY='hidden';
  document.addEventListener("touchmove",mo,false);//禁止页面滑动(出现弹窗)
};
Vue.prototype.canScroll = function () {
  let mo=function(e){e.preventDefault();};
  document.body.style.overflowY='';
  document.getElementById('app').style.overflowY='';
  document.addEventListener("touchmove",mo,false);//允许页面滑动(隐藏弹窗)
};
Vue.prototype.arrRemove = function( arr , delIndex ){
  //删除数组制定下标的元素
  var temArray=[];
  for(var i=0;i<arr.length;i++){
    if(i!=delIndex){
      temArray.push(arr[i]);
    }
  }
  return temArray;
};
Vue.prototype.timeout = function () {
  if( arguments.length == 2 ){
    let time = Number(arguments[1]) || 100;
    let callback = arguments[0] instanceof Function ?  arguments[0] : null;
    if( callback ){
      let newTimeout = null;
      newTimeout = setTimeout(function () {
        callback();
        clearTimeout(newTimeout);
        newTimeout = null;
        time = null;
        callback = null;
      },time)
    }
  }
};
Vue.prototype.checkIDCard = function(idcode) {
  let weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  let check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
  let code = idcode + "";
  let last = idcode[17];//最后一位
  let seventeen = code.substring(0, 17);
  let arr = seventeen.split("");
  let len = arr.length;
  let num = 0;
  for (let i = 0; i < len; i++) {
    num = num + arr[i] * weight_factor[i];
  }
  let resisue = num % 11;
  let last_no = check_code[resisue];
  let idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
  let format = idcard_patter.test(idcode);
  return last === last_no && format ? true : false;
}
Vue.prototype.removeWindowScrollListen = function( callback ){/*页面使用listen scroll监听后，必须销毁*/
  window.removeEventListener('scroll', callback);
};
Vue.prototype.getUrlKey = function (name) {
  if(name){
    function getUrlKey(name , url){
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
    }
    let value = getUrlKey(name, window.location.href) || null;//判断是否有name;
    return value;
  }
};
Vue.prototype.promise = function (callback) {
  return new Promise((resolve , reject) => {
    resolve(callback);
  })
};
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});
